
<template>
<!-- 当我们无法控制某个元素时，可以加一层div去控制 -->
  <div id="login" style="width: 100vw;">
  <el-card class="box-card">
    <h2>后台管理系统</h2>
    <el-radio-group v-model="radio1" size="large" class="raio-button">
      <el-radio-button label="本地认证" />
      <el-radio-button label="AD域控认证" />
      <!-- <el-radio-button label="企业微信认证" /> -->
    </el-radio-group>
    <el-form
      ref="loginRef"
      :model="loginInfo"
      :rules="rules"
    >
      <el-form-item prop="username" class="from-item">
        <el-input clearable :prefix-icon="User" v-model="loginInfo.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item prop="password" class="from-item">
        <el-input show-password :prefix-icon="Lock" v-model="loginInfo.password" type="password" autocomplete="off" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item>
        <el-button style="margin: 10px auto 10px auto" :disabled="loginButtonDisabled" type="primary" @click="submitForm(ruleFormRef)"
          >登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  </div>
</template>
<script setup>
import { reactive, ref, watch} from 'vue'
// 导入图标
import {User, Lock} from '@element-plus/icons-vue'
// 导入消息提示弹框
import { ElMessage } from 'element-plus'
// import request from '../api/index.js'
import { login } from '../api/login.js'
import { CONFIG } from '../config/index.js'
import { useRouter } from 'vue-router'
import { fetchMenus } from '../api/menus.js'
import JSEncrypt from 'jsencrypt';
const loginRef = ref()
const loginInfo = reactive({
     username: "",
     password: "",
})
let labelname = "LOCAL"
const radio1 = ref('本地认证')
const radiolabelname = ref('');
watch(radio1, (newVal) => {
  radiolabelname.value = newVal;
  console.log('当前选中的label:', radiolabelname.value);
  if (radiolabelname.value === "本地认证"){
    labelname="LOCAL"
  } else if (radiolabelname.value === "AD域控认证"){
    labelname="AD"
  }       
});

const router = useRouter()
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur'},
    { min: 8, message: '输入密码最少8位', trigger: 'blur' },
  ],
})
let loginButtonDisabled = ref(true)
// 监听username和password的输入情况
watch([()=> loginInfo.username,()=> loginInfo.password],()=>{
    loginRef.value.validate((valid)=>{
       // valid 是true
       if (valid) {
          // 表单校验成功
          loginButtonDisabled.value = false
       } else {
          // 表单校验失败
          loginButtonDisabled.value = true
       }
    })
})

async function encryptData(username, password) {
  // 获取服务器的公钥（通常是从后端获取）
  const publicKey = CONFIG.PublicKey
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey);

  // 使用公钥加密用户名和密码
  const encryptedUsername = encrypt.encrypt(username);
  const encryptedPassword = encrypt.encrypt(password);

  return { encryptedUsername, encryptedPassword };
}

// 实现一个登录的接口
const submitForm = async() => {
  console.log("loginInfo:", loginInfo)
  const { encryptedUsername, encryptedPassword } = await encryptData(loginInfo.username,loginInfo.password);
   await login(labelname,encryptedUsername,encryptedPassword).then((response)=>{
      console.log("登录response：", response)
      if (response.data.status == 200){
        // 拿到token
        const token= response.data.data.token
        // 将token存储在本地
        window.localStorage.setItem(CONFIG.TOKEN_NAME, token)
        window.localStorage.setItem("loginType", labelname)
        window.localStorage.setItem("loginName", loginInfo.username)
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
        // 获取菜单
        // const result = fetchMenus(labelname,loginInfo.username)
        
        // 登录成功，跳转到首页
        
        router.replace("/")
        
      }
  }).catch((err)=>{
      console.log("登录错误：", err)
  })
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
  margin: 0 auto 300px auto;
}
.from-item{
  width: 240px;
  margin: 0 auto 20px auto;
}
.raio-button{
  width: 240px;
  margin: 0 auto 10px auto;
}
</style>
